package The17;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.Charset;


/**
 * @Author XiaoKe
 * @Date 2020/4/29 20:41
 * @Description NIO的实现非阻塞通信
 */
public class NServer {
    // 用于检测所有Channel状态的selector
    private Selector selector = null;
    static final int PORT = 30000;
    // 定义实现编码，解码的字符集对象

    public void init() throws IOException {
        selector = Selector.open();
        // 用open方法打开一个未绑定的ServerSocketChannel实例
        ServerSocketChannel server = ServerSocketChannel.open();
        InetSocketAddress isa = new InetSocketAddress("127.0.0.1", PORT);
        // 将该channel绑定到指定的IP地址
        server.bind(isa);
        // 设置ServerSocket以非阻塞方式工作
        server.configureBlocking(false);
        // 将server注册到Selector
        server.register(selector, SelectionKey.OP_ACCEPT);
        while (selector.select() > 0) {
            // 依次处理selector上的每个已选择的key
            for (SelectionKey sk : selector.selectedKeys()) {
                // 从selector上的已选择key中删除正在处理的key
                selector.selectedKeys().remove(sk);
                // 如果sk对应的channel包含客户端连接请求
                if (sk.isAcceptable()) {
                    // 调用accept方法接受连接
                    SocketChannel sc = server.accept();
                    sc.configureBlocking(false);
                    // 将该channel注册到selector
                    sc.register(selector, SelectionKey.OP_READ);
                    sk.interestOps(SelectionKey.OP_ACCEPT);
                }
                // 如果sk对应的channel有数据需要读取
                if (sk.isReadable()) {
                    SocketChannel sc = (SocketChannel) sk.channel();
                    // 定义准备执行读取数据的ByteBuffer
                    ByteBuffer buff = ByteBuffer.allocate(1024);
                    String content = "";
                    try {
                        while (sc.read(buff) > 0) {
                            buff.flip();
                            content += buff;
                        }
                        System.out.println("读取的数据：" + content);
                        sk.interestOps(SelectionKey.OP_READ);
                    } catch (IOException ex) {
                        sk.cancel();
                        if (sk.channel() != null) {
                            sk.channel().close();
                        }
                    }

                    if (content.length() >0) {
                        for (SelectionKey key : selector.keys()) {
                            Channel targetChannel = key.channel();
                            if (targetChannel instanceof SocketChannel) {
                                SocketChannel dest = (SocketChannel) targetChannel;
                                dest.write(buff);
                            }
                        }
                    }
                }
            }
        }
    }
}
